package com.mycompany.myapp.web.rest;

import com.mycompany.myapp.repository.UserClassRepository;
import com.mycompany.myapp.service.UserClassService;
import com.mycompany.myapp.service.dto.UserClassDTO;
import com.mycompany.myapp.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link com.mycompany.myapp.domain.UserClass}.
 */
@RestController
@RequestMapping("/api")
public class UserClassResource {

    private final Logger log = LoggerFactory.getLogger(UserClassResource.class);

    private static final String ENTITY_NAME = "userClass";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final UserClassService userClassService;

    private final UserClassRepository userClassRepository;

    public UserClassResource(UserClassService userClassService, UserClassRepository userClassRepository) {
        this.userClassService = userClassService;
        this.userClassRepository = userClassRepository;
    }

    /**
     * {@code POST  /user-classes} : Create a new userClass.
     *
     * @param userClassDTO the userClassDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new userClassDTO, or with status {@code 400 (Bad Request)} if the userClass has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/user-classes")
    public ResponseEntity<UserClassDTO> createUserClass(@RequestBody UserClassDTO userClassDTO) throws URISyntaxException {
        log.debug("REST request to save UserClass : {}", userClassDTO);
        if (userClassDTO.getId() != null) {
            throw new BadRequestAlertException("A new userClass cannot already have an ID", ENTITY_NAME, "idexists");
        }
        UserClassDTO result = userClassService.save(userClassDTO);
        return ResponseEntity
            .created(new URI("/api/user-classes/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /user-classes/:id} : Updates an existing userClass.
     *
     * @param id the id of the userClassDTO to save.
     * @param userClassDTO the userClassDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated userClassDTO,
     * or with status {@code 400 (Bad Request)} if the userClassDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the userClassDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/user-classes/{id}")
    public ResponseEntity<UserClassDTO> updateUserClass(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody UserClassDTO userClassDTO
    ) throws URISyntaxException {
        log.debug("REST request to update UserClass : {}, {}", id, userClassDTO);
        if (userClassDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, userClassDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!userClassRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        UserClassDTO result = userClassService.save(userClassDTO);
        return ResponseEntity
            .ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, userClassDTO.getId().toString()))
            .body(result);
    }

    /**
     * {@code PATCH  /user-classes/:id} : Partial updates given fields of an existing userClass, field will ignore if it is null
     *
     * @param id the id of the userClassDTO to save.
     * @param userClassDTO the userClassDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated userClassDTO,
     * or with status {@code 400 (Bad Request)} if the userClassDTO is not valid,
     * or with status {@code 404 (Not Found)} if the userClassDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the userClassDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/user-classes/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<UserClassDTO> partialUpdateUserClass(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody UserClassDTO userClassDTO
    ) throws URISyntaxException {
        log.debug("REST request to partial update UserClass partially : {}, {}", id, userClassDTO);
        if (userClassDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, userClassDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!userClassRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<UserClassDTO> result = userClassService.partialUpdate(userClassDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, userClassDTO.getId().toString())
        );
    }

    /**
     * {@code GET  /user-classes} : get all the userClasses.
     *
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of userClasses in body.
     */
    @GetMapping("/user-classes")
    public ResponseEntity<List<UserClassDTO>> getAllUserClasses(Pageable pageable) {
        log.debug("REST request to get a page of UserClasses");
        Page<UserClassDTO> page = userClassService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /user-classes/:id} : get the "id" userClass.
     *
     * @param id the id of the userClassDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the userClassDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/user-classes/{id}")
    public ResponseEntity<UserClassDTO> getUserClass(@PathVariable Long id) {
        log.debug("REST request to get UserClass : {}", id);
        Optional<UserClassDTO> userClassDTO = userClassService.findOne(id);
        return ResponseUtil.wrapOrNotFound(userClassDTO);
    }

    /**
     * {@code DELETE  /user-classes/:id} : delete the "id" userClass.
     *
     * @param id the id of the userClassDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/user-classes/{id}")
    public ResponseEntity<Void> deleteUserClass(@PathVariable Long id) {
        log.debug("REST request to delete UserClass : {}", id);
        userClassService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
            .build();
    }
}
